<style>
    .chat-wrap {
        font-size: 14px;
        background: #fff;
        padding: 10px;
        padding-bottom: 55px;
    }

    .chat-wrap.bq-bottom {
        padding-bottom: 210px;
    }

    .chat-wrap.pic-bottom {
        padding-bottom: 130px;
    }

    .chat-wrap .list {
        padding-bottom: 20px;
    }


    /* 头像 */
    .chat-wrap .tx {
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        width: 40px;
        height: 40px;
    }

    .chat-wrap .tx.img-w img {
        width: 40px;
    }

    .chat-wrap .tx.img-h img {
        height: 40px;
    }

    /* 内容 */
    .chat-wrap .c-wrap {
        display: flex;
        align-items: flex-start;
    }

    .chat-wrap .c-wrap.my {
        justify-content: flex-end;
    }

    .chat-wrap .c-wrap.my .tx {
        margin-right: 0;
        margin-left: 10px;
        order: 2;
    }

    .chat-wrap .content {
        background: #eee;
        padding: 5px;
        max-width: 60vw;
        border-radius: 5px;
        order: 1;
        word-break: break-all;
    }

    /* 图片 */
    .chat-wrap .c-wrap .img {
        width: calc(60vw - 20px);
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
    }

    .chat-wrap .c-wrap .img img {
        width: calc(60vw - 20px);
    }

    /* 红包 */
    .red-wrap .content {
        background: #fff;
        color: #fff;
    }

    .red-wrap .content .red-img {
        background-image: url('../image/icon/bg_luckybagdialog.png');
        background-repeat: no-repeat;
        background-size: 100% 100%;
        width: 216px;
        height: 72px;
    }

    .red-wrap .content .red-img-no {
        background-image: url('../image/icon/mp_bg_luckybagdialog_d.png');
    }

    .red-wrap .red-word {
        margin-left: 55px;
        padding-top: 15px;
    }

    .my .red-wrap .red-word {
        margin-left: 0;
        margin-right: 55px;
    }

    .red-wrap .content .red-text {
        color: #f5d03d;
        font-size: 14px;
    }

    .red-wrap .content .red-status {
        font-size: 12px;
    }

    /* 输入框 */
    #input-footer {
        padding: 10px 5px;
        background: #eee;
        position: fixed;
        bottom: 0;
        width: calc(100vw - 10px);
        max-width: 750px;
        min-width: 320px;
    }

    .input-wrap {
        align-items: flex-end;
    }

    .input-wrap .input {
        border: 1px solid #ddd;
        border-radius: 5px;
        padding: 7px 5px;
        background: #fff;
        font-size: 14px;
        width: calc(100vw - 20px - 80px - 2px);
    }

    .input-wrap .send-btn {
        background: #673AB7;
        color: #fff;
        font-size: 14px;
        padding: 7px 3px;
        word-break: keep-all;
        margin-left: 10px;
        border-radius: 5px;
    }

    .time {
        font-size: 12px;
        background: #aaa;
        color: #fff;
        border-radius: 3px;
        padding: 5px 10px;
        margin: 10px 0;
    }

    .biaoqing {
        background-image: url('../res/img/face.png');
        background-size: 100%;
        background-position: center;
        background-repeat: no-repeat;
        width: 30px;
        height: 30px;
        margin: 0 5px;
    }

    .biaoqing.jianpan {
        background-image: url('../res/img/jian_pan.png');
    }

    .biaoqing.add {
        background-image: url('../res/img/jia.png');
    }

    /* 删除 */
    .bq-del {
        background-image: url('../res/img/emotion/delete.png');
        position: fixed;
        bottom: 10px;
        right: 10px;
        z-index: 1;
        width: 40px;
        height: 40px;
        background-size: 70% 70%;
        background-repeat: no-repeat;
        background-position: center;
        background-color: #fff;
        border-radius: 5px;
    }

    /* 表情列表 */
    .biaoqing-wrap .bq {
        /* padding-bottom: 50px; */
        max-height: 150px;
        overflow-y: auto;
    }

    .biaoqing-wrap .bq img {
        width: 30px;
        margin: 5px 3px;
    }

    /* 图片面板 */
    #pic-wrap img {
        width: 60px;
        margin-right: 10px;
        margin-top: 10px;
    }

    /* 撤回 */
    .recall {
        font-size: 12px;
        color: #999;
        text-align: center;
        padding: 10px 0;
    }

    /* 红包提示 */
    .hongbao-msg {
        font-size: 12px;
        text-align: center;
        color: #999;
        padding: 10px 0;
    }

    .hongbao-msg .red-span {
        color: orange;
    }
</style>

<div id="view">
    <ul class="wrap chat-wrap" :class="{'bq-bottom':inputType==1, 'pic-bottom':inputType==2}">
        <div v-for="(m, inde) in ffList">
            <p class="flex-c" v-if="m.showtime">
                <span class="time">{{m.time}}</span>
            </p>
            <div class="recall" v-if="m.status == 3">
                <span>该消息已被撤回</span>
            </div>
            <div v-else>
                <div class="hongbao-msg" v-if="m.type==-1 && m.state ==1">
                    <span v-if="m.data.userid == myuserid">{{m.data.touser_name}}领取了你</span>
                    <span v-else>你领取了{{m.data.user_name}}</span>
                    的<span class="red-span" @click="_url({ id: m.data.chat_id }, 'frame0/hong_bao_detail');">红包</span>
                </div>
                <li class="list" v-else>
                    <div class="c-wrap you " :class="{'my':m.self == 1, 'red-wrap': m.type == 5}">
                        <div class="tx img-h" @click="goUserInfo(m)">
                            <img :src="imgurl+m.head_portrait" @load="imgCss(imgurl+m.head_portrait, $event)"
                                onerror="this.onerror=null;this.src='../image/touxiang.png'" alt="">
                        </div>
                        <div class="content" v-if="m.type == 0" v-html="dealContent(m.content)"></div>
                        <div class="content" v-else-if="m.type == 1">
                            <div class="img img-h">
                                <img :src="imgurl+m.content" @load="imgCss(imgurl+m.content, $event)"
                                    onerror="this.onerror=null;this.src='../image/error-img.png'" alt="">
                            </div>
                        </div>
                        <div class="content" v-else-if="m.type == 5" @click="openRed(m)">
                            <div class="red-img" :class="{'red-img-no':m.state==1}">
                                <div class="red-word">
                                    <p class="red-text">{{m.content}}</p>
                                    <p class="red-status" v-if="m.state==0">等待领取</p>
                                    <p class="red-status" v-if="m.state==1">已领取</p>
                                    <p class="red-status" v-if="m.state==2">已过期</p>
                                </div>
                            </div>
                        </div>
                        <div class="content" v-else>[不支持的消息类型]</div>
                    </div>
                </li>
            </div>
            <!-- <li class="list" v-if="m.self == 1">
                <div class="c-wrap my">
                    <div class="content" v-if="m.type == 0" v-html="dealContent(m.content)"></div>
                    <div class="content" v-if="m.type == 1">
                        <div class="img img-h">
                            <img :src="imgurl+m.content" @load="imgCss(imgurl+m.content, $event)" onerror="this.onerror=null;this.src='../image/error-img.png'" alt="">
                        </div>
                    </div>
                    <div class="tx img-h">
                        <img :src="imgurl+m.head_portrait" @load="imgCss(imgurl+m.head_portrait, $event)" onerror="this.onerror=null;this.src='../image/touxiang.png'" alt="">
                    </div>
                </div>
            </li> -->
        </div>
    </ul>
    <footer id="input-footer">
        <div class="input-wrap flex">
            <div class="input" contenteditable="true" onfocus="inputFocus()"></div>
            <div class="biaoqing" :class="{'jianpan': inputType==1}" @click="openEmotion()"></div>
            <div class="biaoqing add" v-if="contentType==0" @click="openPic()"></div>
            <button class="send-btn" v-if="contentType==1" onclick="sendMsg()">发送</button>
        </div>
        <div class="biaoqing-wrap" v-if="inputType==1">
            <ul class="bq flex-w">
                <li class="li" v-for="(e, eIndex) in emotionUrl" @click="addEmotion(e.name);">
                    <img :src="'../res/img/emotion/'+e.name+'.png'" alt="">
                </li>
                <!-- <li class="li">
                    <img src="../res/img/emotion/Expression_1.png" alt="">
                </li> -->
            </ul>
            <!-- <button class="bq-del"></button> -->
        </div>
        <div id="pic-wrap" v-if="inputType==2">
            <ul class="ul flex-w">
                <li class="li" onclick="selectPic()">
                    <img src="../res/img/nim_message_plus_photo_normal.png" alt="">
                </li>
                <li class="li" onclick="_url({touserid:touserid}, 'frame0/fa_hong_bao')">
                    <img src="../res/img/ic_sendluckybag.png" alt="">
                </li>
            </ul>
        </div>
    </footer>
    <input type="file" id="pic" accept="image/*" style="display: none;">
    <div id="js-modal"></div>
</div>
<script src="../script/liaotian/emotion.js"></script>
<script>
    // var myuserid = 304;
    // var touserid = 295;
    var redId = 0;
    var view = new Vue({
        el: '#view',
        data: {
            myuserid: myuserid,
            imgurl: imgurl,
            ffList: [],
            emotionUrl: emotionUrl,
            // ffList: resultJson.data,
            inputType: 0, // 0 显示输入框，表情按钮，1显示表情列表，
            contentType: 0 // 输入框是否有内容 0 无 1 有
        },
        methods: {
            // 跳转 查看用户详情
            goUserInfo: function (data) {
                var uid = data.userid;
                var name = data.name;
                go_userInfo(uid, name);
            },
            _url: function (param, url) {
                _url(param, url);
            },
            // 图片自适应
            imgCss: function (url, event) {
                var e = event.currentTarget;
                imgCss(url, function (w, h) {
                    if (w < h) {
                        $(e).parent().addClass('img-w').removeClass('img-h');
                    }
                })
            },
            // 处理表情
            dealContent: function (str) {
                return getMesge(str);
            },
            // 添加表情
            addEmotion: function (name) {
                var _this = this;
                var url = '../res/img/emotion/' + name + '.png';
                var html = '<img src=' + url + ' border="0" width="25"/>';
                $('.input-wrap .input').append(html);
                judgeShowSend();
            },
            // 打开表情面板
            openEmotion: function () {
                var _this = this;
                _this.inputType = _this.inputType == 1 ? 0 : 1;
                if (_this.inputType == 0) {

                }
            },
            // 打开图片面板
            openPic: function () {
                var _this = this;
                _this.inputType = _this.inputType == 2 ? 0 : 2;
            },
            // 打开红包详情
            openRed: function (data) {
                var id = data.id;
                var uid = data.userid;
                var state = data.state;
                openRed(id, uid, state)
            },

        }
    })
    var touserid = pageParam['touserid'];
    var bottomType = 0; // 是否允许轮询滚动到底部
    judgeLogin();
    // 监听回车
    window.onkeydown = function (e) {
        if (e.keyCode == 13) {
            sendMsg();
        }
    }
    window.onkeyup = function (e) {
        judgeShowSend()
    }
    // 判断是否要显示发送
    function judgeShowSend() {
        var content = $.trim($('.input-wrap .input').html());
        view.contentType = content ? 1 : 0;
    }

    // 获取焦点
    function inputFocus() {
        // _log(111)
        view.inputType = 0;
    }

    // 发送消息
    function sendMsg() {
        var content = $.trim($('.input-wrap .input').html());
        if (!content) {
            _msg('内容不能为空');
            return;
        }
        $('.input-wrap .input').html('');
        content = replaceEmotion(content);
        // _log(content)
        _ajax('c=Privatechat&a=addTalk', function (ret) {
            _log(JSON.stringify(ret))
            if (ret && ret.code == 200) {
                getMsgList(0);
                bottomType = 0;
                view.inputType = 0;
                view.contentType = 0;
            }
        }, {
            content: content,
            type: 0,
            userid: myuserid,
            touserid: touserid,
        })
    }
    getMsgList(0);
    getNewMsg();
    // 滚动到顶部
    _scrollToTop(function () {
        if (heigutgao == 1) {
            pagenum++;
            getMsgList(pagenum);
        }
    })

    // 获取消息列表
    function getMsgList(page) {
        heigutgao = 0;
        pagenum = page;
        _ajax('c=Privatechat&a=getMsgList', function (ret) {
            _log(JSON.stringify(ret))
            if (ret && ret.code == 200) {
                if (page == 0) {
                    view.ffList = [];
                }
                view.ffList = ret.result.concat(view.ffList);
                if (ret.result.length > 0) {
                    heigutgao = 1
                }
            }
        }, {
            userid: myuserid,
            touserid: touserid,
            page: page,
        })
    }
    var msgTime = 1000;
    // 获取新消息
    function getNewMsg() {
        _ajax('c=Privatechat&a=getNewMsg', function (ret) {
            _log(JSON.stringify(ret))
            if (ret && ret.code == 200) {
                if (ret.result.new.length > 0) {
                    view.ffList = view.ffList.concat(ret.result.new);
                }
                var _pageParam = getParam();
                if (_pageParam && _pageParam['url'] == 'frame0/liaotian') {
                    var dt = setTimeout(function () {
                        clearTimeout(dt);
                        dt = null;
                        getNewMsg();
                    }, msgTime)
                }
            } else {
                var dt = setTimeout(function () {
                    clearTimeout(dt);
                    dt = null;
                    getNewMsg();
                }, msgTime)
            }
        }, {
            userid: myuserid,
            touserid: touserid,
            time: 40,
            // urlType: 'get'
        })
    }

    //得到替换后的消息内容
    function getMesge(str) {
        if (!str) {
            return '';
        }
        str = str.replace(/\[(.+?)\]/g, function (a, b) {
            var url = '../res/img/emotion/' + getEmotionUrl(a) + '.png';
            return '<img src=' + url + ' border="0" width="25"/>';
        });
        str = entityToString(str);
        return str;
    }
    // 实体字符转html代码
    function entityToString(entity) {
        // 若无实体字符则不转换
        if (entity.indexOf('&lt' == -1)) return entity;
        var div = document.createElement('div');
        div.innerHTML = entity;
        var res = div.innerText || div.textContent;
        return res;
    }
    //根据表情名获取表情图片路径
    function getEmotionUrl(text) {
        for (var i = 0; i < emotionUrl.length; i++) {
            if (text == emotionUrl[i].text) {
                return emotionUrl[i].name;
            }
        }
    }


    // 滚动到底部
    function goToBottom() {
        if (bottomType == 0) {
            var h = $('.chat-wrap').height();
            $(document).scrollTop(h + 200);
            setTimeout(function () {
                goToBottom();
            }, 500)
        } else {
            setTimeout(function () {
                goToBottom();
            }, 500)
        }
    }
    goToBottom();

    // 判断 滚动到底部时
    window.addEventListener("scroll", function (e) {
        if ($(document).scrollTop() >= $(document).height() - $(window).height() - 10) {
            bottomType = 0;
        } else {
            bottomType = 1;
        }
        _log(bottomType)
    });


    // 替换表情
    function replaceEmotion(content) {
        for (var i = 0, len = emotionUrl.length; i < len; i++) {
            var img = '<img src="../res/img/emotion/' + emotionUrl[i].name + '.png" border="0" width="25">';
            var reg = new RegExp(img, 'gi');
            content = content.replace(reg, emotionUrl[i].text);
        }
        return content;
    }

    // 选择图片
    function selectPic() {
        $('#pic').click();
    }

    // 上传图片
    $('#pic').on('change', function () {
        var formData = new FormData();
        formData.append("file", this.files[0]);
        formData.append("userid", myuserid);
        formData.append("touserid", touserid);
        formData.append("type", 1);
        $.ajax({
            url: phpurl + 'apis/index.php?c=Privatechat&a=addTalk', //请求接口
            type: "POST", //请求方式
            dataType: 'json',
            data: formData, //请求参数（这里将参数都保存在formData对象中）
            processData: false, //因为data值是FormData对象，不需要对数据做处理。
            contentType: false, //默认为true,不设置Content-type请求头
            success: function (result) {
                _log(JSON.stringify(result))
                _loadingClose();
                if (result && result.code == 200) {
                    getMsgList(0);
                    bottomType = 0;
                    view.inputType = 0;
                    view.contentType = 0;
                }
            },
            error: function (err, status) {
                _log(JSON.stringify(err))
            }
        })
    })

    // 查看红包详情

    // 点击红包
    function openRed(id, uid, state) {
        if (uid == myuserid) {
            // 自己发的红包
            _url({
                id: id
            }, 'frame0/hong_bao_detail');
        } else {
            // 对方发的红包
            if (state == 0) {
                redId = id;
                // 未领取
                _load('#js-modal', 'frame0/hong_bao')
            } else {
                // 已领取
                _url({
                    id: id
                }, 'frame0/hong_bao_detail');
            }
        }
    }

    // 关闭模态框
    function closeMoneyFrm() {
        $('#js-modal').addClass('new-hide');
    }
</script>
